<?php
/**
 * 新闻
 */
$url = 'https://way.jd.com/jisuapi/get?channel=头条&num=10&start=0&appkey=e61ea08206439db9cb30910865faad7c';
$resp = news_http_request($url);
if ($resp) {
    build_news_response($resp['list'], 5);
} else {
    echo '没有找到结果, 要不过一会再试试?';
}

/**
 * @param $url
 * @return bool|array
 */
function news_http_request($url)
{
    $ret = curl_http_request($url);
    $resp = json_decode($ret['response'], true);
    // 调试日志
    //file_put_contents(runtime_path() . '/userApi_news.log', __METHOD__ . PP($resp, false));
    if (isset($resp['code']) && (10000 === (int)$resp['code']) && !empty($resp['result']['result']) && !empty($resp['result']['result']['num'])) {
        return $resp['result']['result'];
    }
    return false;
}

/**
 * 打包响应数据
 * @param array $data
 * @param int $num
 */
function build_news_response(array $data = [], int $num = 6)
{
    $i = 1;
    foreach ($data as $k => $item) {
        // 前缀换行
        $prefix = ($i === 1) ? '' : PHP_EOL . PHP_EOL;
        // 输出
        echo sprintf($prefix . ($i++) . '. %s' . PHP_EOL . '%s' . PHP_EOL . '%s (%s)', $item['title'], $item['weburl'], $item['src'], $item['time']);
        if ($i > $num) {
            return;
        }
    }
}
